package com.applcn.user.repo.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.applcn.user.repo.entity.MerchantEntity;
import com.applcn.user.repo.mapper.MerchantMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;

/**
 * com.applcn.user.repo.repository
 * Description:
 *
 * @author: 大妖怪
 * @date: 2020-01-19 18:33
 */
@Repository
public class MerchantRepository extends ServiceImpl<MerchantMapper, MerchantEntity> {

    /**
     * 通过userId查询商户
     *
     * @param userId
     * @return
     */
    public MerchantEntity getByUserId(Long userId) {
        MerchantEntity merchantEntity = baseMapper.selectOne(
                new QueryWrapper<MerchantEntity>()
                        .lambda()
                        .eq(MerchantEntity::getUserId, userId)
        );
        if (Objects.isNull(merchantEntity)) {
            merchantEntity = new MerchantEntity();
            merchantEntity.setUserId(userId);
            baseMapper.insert(merchantEntity);
        }
        return merchantEntity;
    }

    /**
     * 查询商户列表
     *
     * @param pageNum
     * @param pageSize
     * @param merchantIds
     * @param userIds
     * @return
     */
    public IPage<MerchantEntity> pageMerchantByIds(Integer pageNum, Integer pageSize, List<Long> merchantIds, List<Long> userIds) {
        Page<MerchantEntity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<MerchantEntity> wrapper = new QueryWrapper<MerchantEntity>().lambda();
        if (CollectionUtil.isNotEmpty(merchantIds)) {
            wrapper.in(MerchantEntity::getId, merchantIds);
        }

        if (CollectionUtil.isNotEmpty(userIds)) {
            wrapper.in(MerchantEntity::getUserId, userIds);
        }
        return baseMapper.selectPage(
                page,
                wrapper
        );
    }
}
